package demo.socket.client;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 *
 * @author daify
 * @date 2019-08-23 11:01
 **/
public class SocketClient {

    public static void main(String[] args) throws Exception {
        baseSocketClient();
    }

    /**
     * 基础的Socket客户端
     * @throws IOException
     */
    public static void baseSocketClient() throws IOException {
        // 监听地址和端口
        SocketAddress address = new InetSocketAddress("127.0.0.1", 8000);
        try (Socket socket = new Socket()) {
            socket.connect(address);
            
            try (// 获取输入输出流，读写数据（与服务端数据读写操作相同）
                 OutputStream out = socket.getOutputStream();
                 // 获取输入流
                 InputStream in = socket.getInputStream()){
                
                // 写数据
                out.write("hello, server".getBytes());
                // 关闭此处输出流
                socket.shutdownOutput();

                // 解析服务器返回的内容
                String message = getMessage(in);
                // 获得返回的内容
                System.out.println("Server return:" + message); 
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对输入流进行解析获得返回的内容
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static String getMessage(InputStream inputStream) throws IOException {
        // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
            //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
            sb.append(new String(bytes, 0, len,"UTF-8"));
        }
        return sb.toString();
    }
}
